package com.freeman.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jui.core.dynamic.DynamicEngine;

public class DynaRunServlet extends HttpServlet {
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		String src = (String) request.getParameter("src");
 
		System.out.println(src);
		// 得到控制台输出
		// cache stream
		String consoleMsg = null;
		//String errMsg = null;
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(10000);
		PrintStream cacheOutStream = new PrintStream(byteArrayOutputStream);
		//ByteArrayOutputStream byteArrayErrputStream = new ByteArrayOutputStream(10000);
		//PrintStream cacheErrStream = new PrintStream(byteArrayErrputStream);
		// get old stream
		//PrintStream oldSystemErr = System.err;
		PrintStream oldSystemOut = System.out;
		//设置新的out
		System.setOut(cacheOutStream);
		//System.setErr(cacheErrStream);
		//运行
		boolean errorFlag=false;
		try {
			String className="DynaClass";
			String packageName=null;
			
			String classMark = " class ";
			if (src.indexOf(classMark) > 0) {
				int beginIndex = src.indexOf(classMark) + classMark.length();
				String leftStr = src.substring(beginIndex).trim();
				int endIndex = leftStr.indexOf(" ");
				className = leftStr.substring(0, endIndex).trim();
			}
			String packageMark = "package ";
			if (src.indexOf(packageMark) >= 0) {
				int beginIndex = src.indexOf(packageMark) + packageMark.length();
				String leftStr = src.trim().substring(beginIndex).trim();
				int endIndex = leftStr.indexOf(";");
				packageName = leftStr.substring(0, endIndex).trim();
			}
			String fullName = (packageName==null ?"":(packageName+"."))+className;
			DynamicEngine de = DynamicEngine.getInstance();
			Object instance = de.javaCodeToObject(fullName, src.toString());
			Method mainMethod = instance.getClass().getMethod("main", String[].class);
			// 触发main方法
			mainMethod.invoke(instance, (Object) new String[] {});
		} catch (Throwable e) {
			e.printStackTrace();
			errorFlag=true;
		}finally{	
			consoleMsg = byteArrayOutputStream.toString();
			if (errorFlag && consoleMsg.indexOf("Message:")>0){
				consoleMsg=consoleMsg.substring(consoleMsg.indexOf("Message:"));
			}
			//还原为旧的控制台输出
			System.setOut(oldSystemOut);
			//打印程序运行日志
			System.out.println(consoleMsg);
			try {
				cacheOutStream.close();
				byteArrayOutputStream.close();
				//cacheErrStream.close();
				//byteArrayErrputStream.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}

		PrintWriter out = response.getWriter();
		out.println(consoleMsg); // 利用PrintWriter对象的方法将数据发送给客户端
		out.close();
	}

}
